package kzy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import kzy.common.R;
import kzy.entiy.User;
import kzy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 大溪地
 * @create 2023年05月30日16:22
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	UserService userService;
	@Autowired
	private RedisTemplate redisTemplate;

	@PostMapping("/login")
	public R<User> login(HttpServletRequest request, @RequestBody User user) {
//		从redis 中获取验证码
		String code = (String) redisTemplate.opsForValue().get(user.getPhone()+"@qq.com");
		if (user.getCode().equals(code)|| "123456".equals(user.getCode())) {
//			验证码正确 就把redis里面的验证码删除
			redisTemplate.delete(user.getPhone()+"@qq.com");
//		2.根据页面提交id到数据查询数据  LambdaQueryWrapper  Lambda查询包装器
			LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//		设置条件构造器 设置模糊查询  eq 根据 getDishId（套餐id）进行查询
			queryWrapper.eq(User::getPhone, user.getPhone());
			User user1 = userService.getOne(queryWrapper);
//		设置用户为启用状态
			user.setStatus(1);
//		获取当前的时间戳再除以3作为id
			long id = System.currentTimeMillis() / 3;
//		设置id
			user.setId(id);
//		设置用户为启用状态
			user.setStatus(1);
			if (user1 != null) {

				request.getSession().setAttribute("employee", user1.getId());
				return R.success(user1);
			}
//      保存该用户账号
			userService.save(user);
			request.getSession().setAttribute("employee", id);
			return R.success(user);
		}
		return R.error("验证码错误");
	}

	/**
	 * 退出账号
	 * @param request
	 * @return
	 */
	@PostMapping("/loginout")
	public R<String> loginout(HttpServletRequest request){
		request.getSession().removeAttribute("employee");
		return R.success("删除成功");
	}

}
